import random
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import jwt
import datetime
from django.http import JsonResponse
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings

def check_code(width=128, height=38, char_length=5, font_file='app_user/static/fonts/中易隶书.TTF', font_size=28):
    code = []
    img = Image.new(mode='RGB', size=(128, 30), color=(255, 255, 255))
    draw = ImageDraw.Draw(img, mode='RGB')

    def rndChar():
        """"""
        """随机生成文字"""
        return chr(random.randint(65, 90))

    def rndcolor():
        """"""
        """随机颜色"""
        return (random.randint(0, 255), random.randint(10, 255), random.randint(64, 255))

    font = ImageFont.truetype(font_file, font_size)
    for i in range(char_length):
        char = rndChar()
        code.append(char)
        h = random.randint(0, 4)
        draw.text([i * width / char_length, h], char, font=font, fill=rndcolor())

    # 干扰点
    for i in range(40):
        draw.point([random.randint(0, width), random.randint(0, height)], fill=rndcolor())

    img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
    return img, "".join(code)



def create_token(user_id, expiration_minutes=30):
    """生成token"""
    playload = {
        'user_id': user_id,
        'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=expiration_minutes)
    }
    token = jwt.encode(playload, settings.SECRET_KEY, algorithm='HS256')
    return token



def verify_token(token):
    """验证token"""
    try:
        payload = jwt.decode(token, settings.SECRET_KEY, algorithms='HS256')
        return payload['user_id']
    except jwt.ExpiredSignatureError:
        return "Token has expired"
    except jwt.InvalidTokenError:
        return "Invalid token"

